/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trocabi.Socle;

/**
 *
 * @author philippe
 */
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class JStringTextField extends JFormattedTextField implements KeyListener {
    private int     maxSize;
    private boolean uppercase;

    public JStringTextField(int maxSize,boolean uppercase) {
        super();
        this.maxSize = maxSize;
        this.uppercase=uppercase;
        
        addKeyListener(this);
        setText("");
    }

    @Override
    public void keyTyped(KeyEvent ke) {
    }

    @Override
    public void keyPressed(KeyEvent ke) {
    }

    @Override
    public void keyReleased(KeyEvent ke) {
        String text = this.getText();
           
        if (uppercase)               text=text.toUpperCase();
        if (text.length() > maxSize) text=text.substring(0, text.length() - 1);
        
     super.setText(text);
    }

    public void setText(String value) {
        super.setText(value);
        this.setCaretPosition(0);
    }
    /**
     * Sample usage
     *
     * @param args
     * @throws ParseException
     */
    public static void main(final String args[]) throws ParseException {
        JFrame frame = new JFrame("Formatted Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JStringTextField stringTextField = new JStringTextField(10,true);
        //numberTextField.setNumber(1234);
        JTextField simpleText = new JTextField();
        frame.add(stringTextField, BorderLayout.NORTH);
        frame.add(simpleText, BorderLayout.SOUTH);
        frame.setSize(250, 100);
        frame.setVisible(true);
    }
}